package org.new9uy.tetris.controller;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import org.new9uy.tetris.GameConstants;
import org.new9uy.tetris.GameData;
import org.new9uy.tetris.Settings;
import org.new9uy.tetris.game.player.Human;
import org.new9uy.tetris.game.type.Game;
import org.new9uy.tetris.game.player.Player;
import org.new9uy.tetris.util.SwingUtils;
import org.new9uy.tetris.view.LobbyPanel;
import org.new9uy.tetris.view.PlayerPanel;
import org.new9uy.tetris.view.PostGamePanel;
import org.new9uy.tetris.view.SettingsDialog;


public class GUIController 

    //implements ActionListener, WindowListener
{
    /*
    public static GUIController current;
    
    private static State STATE = State.MENU;
    
    private JFrame mainFrame;
    //private LobbyPanel lobby;
    private JPanel total;
    private JPanel welcome;
    
    private JMenuBar menuBar = new JMenuBar();
    private JMenu menu = new JMenu("Menu");
    private JMenu about;
    private JMenuItem settings;
    
    private PlayerPanel playerPanel;
    
    private JButton singlePlayer;
    private JButton demoGame;
    private JButton exitP;
    private int startlvl = 0;
    
   
    private KeyListener kc = null;

    public GUIController()
    {
        mainFrame = new JFrame("Multitris");
        
        mainFrame.setIconImage(GameConstants.IMAGE_ICON.getImage());

        try
        {
            GameData.load();
        } 
        catch (FileNotFoundException e)
        {
            String name =
                    SwingUtils.showInputDialog(mainFrame, "New Profile", "Enter your name:");
            Settings.useDefaultControls();
            Settings.PLAYER_NAME = name;
            
            GameData.save(name,
                    new int[]
            {
                Settings.CONTROLLER_DROP,
                Settings.CONTROLLER_LEFT,
                Settings.CONTROLLER_RIGHT,
                Settings.CONTROLLER_SPEEDUP,
                Settings.CONTROLLER_ROTATE
            });
        }

        about = new JMenu("About");
        settings = new JMenuItem("Setting");

        settings.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
		SettingsDialog dialog = new SettingsDialog(mainFrame);
		dialog.setVisible(true);
		dialog.pack();///??????
            }
        });

        playerPanel = new PlayerPanel(new Human(Settings.PLAYER_NAME));

        createMenu();
        buildWelcome();

        registrate();

        update(welcome);
    }
    
    public void show()
    {
	mainFrame.setVisible(true);
    }
    
    private void registrate()
    {
        mainFrame.addWindowListener(this);
        current = this;
        
        singlePlayer.addActionListener(this);
        exitP.addActionListener(this);
    }

    private void createMenu()
    {
        //ABOUT MENU
        JMenuItem about0 = new JMenuItem("Multitris");
        JMenuItem back = new JMenuItem("Home");
        about.add(about0);
        
        about0.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                SwingUtils.infoMessage(mainFrame,
                        "Multitris is a free multi-player video game  inspired by the orginal game\n"
                        + "Tetris. It was designed and programmed by Olivier Legat and Adrien Bibal\n"
                        + "in 2010. Redistribution of this game is permitted but modifying it's\n"
                        + "content is prohibited.\n\n"
                        + "---Credits:---\n"
                        + "Game Design + Programming:   Olivier Legat & Adrien Bibal\n\n"
                        + "Tetris Main Theme:   Tetris Corperation (c)\n"
                        + "Lion-Heart:   Chafic Mekkaoui\n"
                        + "Other midi songs:   Olivier Legat\n\n"
                        + "Voicing:   Olivier Legat\n"
                        + "Other sound effects downloaded from free sources.\n",
                        "About Multitris - A Multi-player Tetris game in Java 6");
            }
        });
        
        back.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                returnToWelcome();
            }
        });

        menu.add(back);
        menuBar.add(menu);
        menuBar.add(about);

        this.mainFrame.setJMenuBar(menuBar);
    }

    public static State getState()
    {
        return STATE;
    }

    public void returnToWelcome()
    {
        exitLobby();
        update(welcome);
        STATE = State.MENU;
    }

    // Initializes welcome panel
    private void buildWelcome()
    {
        STATE = State.MENU;
        menu.add(settings);
        welcome = new JPanel(new GridLayout(2, 1));
        JLabel tetrisParty = new JLabel(
                new ImageIcon(GameConstants.IMAGE_WELCOME.getImage()));
        welcome.setBackground(Color.BLACK);
        welcome.add(tetrisParty);

        JPanel buttons = new JPanel();
        buttons.setLayout(new FlowLayout());
        buttons.setBackground(Color.BLACK);

        
        singlePlayer = SwingUtils.newDefaultButton("Single Player");
        exitP = SwingUtils.newDefaultButton("Exit");

        buttons.add(singlePlayer);
        buttons.add(exitP);

        welcome.add(buttons);
        welcome.setPreferredSize(GameConstants.WIN_PREFERRED_DIM);
    }

    private void buildLobby()
    {
        STATE = State.LOBBY;
        menuBar.remove(settings);
    }

    // Initializes tetris (total) panel
    private void buildTetris()
    {
        STATE = State.INGAME;

        Settings.START_LEVEL = startlvl;

        int x;
        int y;
        int z = 0;
        for (int p = 0; p < 4; p++)
        {
            if (closed[p] == false)
            {
                z++;
            }
        }
        if (z == 1)
        {
            x = 1;
            y = 1;
        } else
        {
            if (z == 2)
            {
                x = 2;
                y = 1;
            } else
            {
                x = 2;
                y = 2;
            }
        }

        total = new JPanel(new GridLayout(y, x));

        for (int i = 0; i < 4; i++)
        {
            if (!closed[i])
            {
                ppan[i] = new PlayerPanel(i, lobby.isBot(i), lobby.getPlayerName(i));
                ppan[i].setTeamColor(teamcolors[i]); //3) et ceci.
                total.add(ppan[i]);
            } else
            {
                ppan[i] = null;
            }
        }
    }

    private void update(JPanel after)
    {
        mainFrame.setVisible(false);
        mainFrame.getContentPane().removeAll();
        mainFrame.add(after);
        mainFrame.pack();
        mainFrame.setVisible(true);
        mainFrame.requestFocusInWindow();
    }

    public void refreshData(int player)
    {
        ppan[player].refreshData();
    }

    public void launchGame(Game game)
    {
        TCPSocket sock = lobby.getTCPSocket();
        buildTetris();
        update(total);
        sock.startGame(game);
        //TODO: DANGER!!! Ce KeyController risque de rester dans les jeux qui suit.
        addKeyListener(game.getPlayer(sock.getPlayerNum()));
    }

    private void addKeyListener(Player me)
    {
        if (kc != null)
        {
            mainFrame.removeKeyListener(kc);
        }

        kc = new KeyController(me.getMatrix(), me.getGravity());
        mainFrame.addKeyListener(kc);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() instanceof JButton)
        {
            onJButton((JButton) (e.getSource()));
        }

        if (e.getSource() instanceof JComboBox)
        {
            onJComboBox((JComboBox) e.getSource());
        }

        if (e.getSource() instanceof JCheckBox)
        {
            onJCheckBox((JCheckBox) e.getSource());
        }
    }

    //---------------------------------------
    // JComponent tasks :
    //---------------------------------------
    private void onJButton(JButton jb)
    {
	if (jb == singlePlayer)
	{
	    onSinglePlayer();
	}
	else if (jb == demoGame)
	{
	    onMultiPlayer();
	}
	else if (jb == exitP)
	{
	    onExit();
	}
	else if (jb == lobby.getStartButton())
	{
	    onStart();
	}

    }

    private void onJComboBox(JComboBox jcb)
    {
        if (jcb == lobby.getStartLevel())
        {
            String select = (String) jcb.getSelectedItem();

            startlvl = Integer.decode(select);

        } else
        {
            if (jcb == lobby.getBotlvl())
            {
                String select = (String) jcb.getSelectedItem();
                String[] dif = Settings.INTERFACE_LANG.botDifficulty();

                if (select.equals(dif[0]))
                {
                    Settings.DIFFICULTY = 1;
                }
                if (select.equals(dif[1]))
                {
                    Settings.DIFFICULTY = 2;
                }
                if (select.equals(dif[2]))
                {
                    Settings.DIFFICULTY = 3;
                }
                if (select.equals(dif[3]))
                {
                    Settings.DIFFICULTY = 4;
                }
            }
        }
        onSlot(jcb);
    }

    private void onJCheckBox(JCheckBox jcb)
    {
        onReady(jcb);
    }

    private void onSinglePlayer()
    {
        buildLobby();
        lobby.prepareForSinglePlayer();
        lobby.setPlayerName(Settings.PLAYER_NAME);
        update(lobby);
    }

    private void onDemoGame()
    {
        ////////////////////
    }

    private void onExit()
    {
        //TODO: notify host/client.
        System.exit(0);
    }

    private void onStart()
    {
        launchGame(lobby.makeGame());
    }

    @SuppressWarnings("unused")
    private void onBack()
    {
    }

    private void onSlot(JComboBox jcb)
    {
        for (int i = 0; i < 4; i++)
        {
            if (jcb == lobby.getSlots()[i])
            {
                String select = (String) jcb.getSelectedItem();

                if (select.equals(Settings.INTERFACE_LANG.human()))
                {
                    lobby.setHuman(i);
                } else
                {
                    if (select.equals(Settings.INTERFACE_LANG.bot()))
                    {
                        lobby.setBot(i);
                    } else
                    {
                        if (select.equals(Settings.INTERFACE_LANG.closed()))
                        {
                            lobby.setClosed(i);
                        }
                    }
                }
            }
        }
    }

    private void onReady(JCheckBox jcb)
    {
        lobby.updateStartButton();
        lobby.notifyReadyChange(jcb);
    }

    public void dcFromSvrMsg()
    {
        SwingUtils.infoMessage(mainFrame, Settings.INTERFACE_LANG.disconnectFrom(),
                Settings.INTERFACE_LANG.disconnection());
    }

    public void kickFromSvrMsg()
    {
        SwingUtils.infoMessage(mainFrame, Settings.INTERFACE_LANG.kickFromTheServer(),
                Settings.INTERFACE_LANG.disconnection());
    }

    public void postGameCarnage(boolean won, Player[] plyrs)
    {
        JPanel p = new PostGamePanel(won, plyrs);
        //TODO: play win/lose sound :P
        update(p);
    }
    //2) et ca... 


    @Override
    public void windowActivated(WindowEvent e)
    {
        
    }

    @Override
    public void windowClosed(WindowEvent e)
    {
        
    }

    @Override
    public void windowClosing(WindowEvent e)
    {
        exitApp();
    }

    @Override
    public void windowDeactivated(WindowEvent e)
    {
        
    }

    @Override
    public void windowDeiconified(WindowEvent e)
    {
        
    }

    @Override
    public void windowIconified(WindowEvent e)
    {
        
    }

    @Override
    public void windowOpened(WindowEvent e)
    {
        
    }
    * */
}
